import struct
import requests
from datetime import  datetime, timedelta

def getTm( tmStr):
    t = (tmStr[0:19]).replace('T',' ')
    dt = datetime.strptime(t,'%Y-%m-%d %H:%M:%S')
    dt = dt + timedelta(hours=8)
    tm = int(dt.timestamp())*1000*1000*1000
    return tm



import json
initData = [
    [1113,562,'lyModPower1',421730.4],
    [1114,563,'lyModPower2',428317.2],
    [1115,564,'lyModPower3',407803.2],
    [1116,565,'lyModPower4',419671.1],
    [1118,551,'ly645',12516480],
    [1119,552,'ly645',777720],
    [1677,567,'wx64501',14204]
]

his=[
    [1676,566,'wx64501'],
    [1677,567,'wx64501'],
    [1678,568,'wx64501'],
    [1679,569,'wx64501'],
    [1680,570,'wx64501'],
    [1681,571,'wx64501'],
    [1682,572,'wx64501'],
    [1683,573,'wx64501'],
    [1684,574,'wx64501'],
    [1685,575,'wx64501'],
    [1686,576,'wx64501'],
    [1687,577,'wx64501'],
]


token = "Basic cm9vdDpoaHVjMTExNQ=="
url="http://meeting.xmgkfw.com:42036"
urliot="http://iot.zn-power.com:30111"
db="pcs2023"
def getInitPointa():
    res =[]
    for item in initData:
        pt=f"{item[2]},vid={str(item[1])} v={item[3]} {getTm('2024-12-31T16:00:01Z')}"
        res.append(pt)
    return  res

def getHisData():
    res =[]
    for item in his:
        sql = f"select  v  from variots  where vid='{item[0]}' and time>='2025-01-09T16:00:00Z' order by time  limit 20000"

        headers = {
            "Authorization": token,
            'Content-Type': 'application/json',
        }
        influxdb_url = url + '/query?db=' + db
        influxdb_url = influxdb_url + "&q=" + sql
        resp = requests.get(url=influxdb_url, headers=headers)
        resJson = resp.json()
        values = []
        try:
            values = resJson['results'][0]['series'][0]['values']
        except Exception as ee:
            print('his error' , item)
            print(ee)
        if len(values)>0:
            for val in values:
                v = str(val[1])
                if len(str(v))>12:
                    v=f"{val[1]:.2f}"
                pt=f"{item[2]},vid={str(item[1])} v={v}  {getTm(val[0])} "
                res.append(pt)
    return res


init = getInitPointa()

hisData = getHisData()

pts = init + hisData
print(pts)

protocolPoints = "\n".join(pts)

headers = {
    "Authorization": token,
    'Content-Type': 'application/json',
}
influxdb_url = urliot + '/write?db=zniot2025'

resp = requests.post(url=influxdb_url, headers=headers, data=protocolPoints)
print(resp)
